package com.rookie.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rookie.common.exception.CaptchaException;
import com.rookie.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private LoginFailtureHandler loginFailtureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String url = httpServletRequest.getRequestURI();
        if ("/login".equals(url) && httpServletRequest.getMethod().equals("POST")) {
            try {
                // 校验验证码
                String code = httpServletRequest.getParameter("code");
                String key = httpServletRequest.getParameter("key");
                if (StringUtils.isBlank(code) || StringUtils.isBlank(key)) throw new CaptchaException("验证码错误");
                if (!code.equals(redisUtil.hget("captcha", key))) throw new CaptchaException("验证码错误");
            } catch (CaptchaException e) {
                // 交给认证失败处理器处理
                loginFailtureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}
